package com.itdfq.upload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

/**
 * @Author GocChin
 * @Date 2021/4/14 12:39
 * @Blog: itdfq.com
 * @QQ: 909256107
 */
@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpSession session) throws Exception {
        // 打印文件的名称
        System.out.println("FileName:" + file.getOriginalFilename());
        //将名字存到session中
        session.setAttribute("photoName", file.getOriginalFilename());

        // 确定上传文件的位置
        // 本地路径,测试确实能通过
        // String path = "E:/temp/temp";
        // Linux系统
//        String path = "/usr/CBeann/temp";
        String path="D:\\upload";
        // 获取上传的位置（存放图片的文件夹）,如果不存在，创建文件夹
        File fileParent = new File(path);
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        File newFile = new File(path + "/", file.getOriginalFilename());
        // 如果不存在，创建一个副本
        if (!newFile.exists()) {
            newFile.createNewFile();

        }
        // 将io上传到副本中
        file.transferTo(newFile);

        return "/success";


    }
    //跳转到success.html页面
    @RequestMapping("/success")
    public String successHtml(){
        return "success";
    }

    @RequestMapping("/showimage")
    public String showphoto(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 获得的系统的根目录
        File fileParent = new File(File.separator);
        String photoName = (String) session.getAttribute("photoName");
        // 获得/usr/CBeann目录(LInux虚拟机目录)
//        File file = new File(fileParent, "D:\\upload" + photoName);

        File file = new File( "D:\\upload\\" + photoName);
        BufferedImage bi = ImageIO.read(new FileInputStream(file));
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;

    }


}
